import React, { useState, useEffect } from 'react';
import { Paper, Typography, Button, Box, Dialog, DialogTitle, DialogContent, DialogActions, TextField, Slider, Alert, Snackbar } from '@mui/material';
import { useAppSelector, useAppDispatch } from '../../store/store';
import { clearError, updatePlayerActions, setIsPlayerTurn } from '../../store/gameSlice';
import gameService from '../../services/gameService';

interface GameControlsProps {
  gameId: string;
  currentBet: number;
  playerChips: number;
  canCheck: boolean;
  canCall: boolean;
  canRaise: boolean;
  canFold: boolean;
  canAllIn: boolean;
  minBet?: number;  // 添加最小下注额属性
  bigBlind?: number; // 添加大盲注属性
}

const GameControls: React.FC<GameControlsProps> = ({
  gameId,
  currentBet,
  playerChips,
  canCheck,
  canCall,
  canRaise,
  canFold,
  canAllIn,
  minBet = 10,    // 默认最小下注额
  bigBlind = 20    // 默认大盲注
}) => {
  const dispatch = useAppDispatch();
  // 从Redux store获取状态
  const { isLoading, error, currentGame } = useAppSelector(state => state.game);
  const { user } = useAppSelector(state => state.auth);
  const currentPlayerId = user?.id ? parseInt(user.id) : (currentGame?.players[0]?.id ? parseInt(currentGame.players[0].id) : undefined);
  
  // 本地状态
  const [raiseDialogOpen, setRaiseDialogOpen] = useState(false);
  const [allInDialogOpen, setAllInDialogOpen] = useState(false);
  const [raiseAmount, setRaiseAmount] = useState(Math.max(currentBet * 2, bigBlind * 2)); // 使用大盲注的2倍作为最小加注
  const [localError, setLocalError] = useState<string | null>(null);

  // 当currentBet或bigBlind变化时，更新raiseAmount
  useEffect(() => {
    setRaiseAmount(Math.max(currentBet * 2, bigBlind * 2));
  }, [currentBet, bigBlind]);

  // 处理过牌
  const handleCheck = async () => {
    try {
      setLocalError(null);
      dispatch(clearError());
      
      dispatch(updatePlayerActions({
        canCheck: false,
        canCall: false,
        canRaise: false,
        canFold: false,
        canAllIn: false
      }));
      dispatch(setIsPlayerTurn(false));
      
      await gameService.makeGameAction(gameId, { 
        type: 'check',
        playerId: currentPlayerId
      });
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '过牌失败';
      console.error('Check failed:', error);
      setLocalError(errorMessage);
      
      // 恢复按钮状态
      dispatch(updatePlayerActions({
        canCheck,
        canCall,
        canRaise,
        canFold,
        canAllIn
      }));
      dispatch(setIsPlayerTurn(true));
    }
  };

  // 处理跟注
  const handleCall = async () => {
    try {
      setLocalError(null);
      dispatch(clearError());
      
      dispatch(updatePlayerActions({
        canCheck: false,
        canCall: false,
        canRaise: false,
        canFold: false,
        canAllIn: false
      }));
      dispatch(setIsPlayerTurn(false));
      
      await gameService.makeGameAction(gameId, { 
        type: 'call',
        playerId: currentPlayerId
      });
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '跟注失败';
      console.error('Call failed:', error);
      setLocalError(errorMessage);
      
      // 恢复按钮状态
      dispatch(updatePlayerActions({
        canCheck,
        canCall,
        canRaise,
        canFold,
        canAllIn
      }));
      dispatch(setIsPlayerTurn(true));
    }
  };

  // 处理加注
  const handleRaise = async () => {
    try {
      setLocalError(null);
      dispatch(clearError());
      
      setRaiseDialogOpen(false);
      
      dispatch(updatePlayerActions({
        canCheck: false,
        canCall: false,
        canRaise: false,
        canFold: false,
        canAllIn: false
      }));
      dispatch(setIsPlayerTurn(false));
      
      await gameService.makeGameAction(gameId, { 
        type: 'raise', 
        amount: raiseAmount,
        playerId: currentPlayerId
      });
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '加注失败';
      console.error('Raise failed:', error);
      setLocalError(errorMessage);
      
      // 恢复按钮状态
      dispatch(updatePlayerActions({
        canCheck,
        canCall,
        canRaise,
        canFold,
        canAllIn
      }));
      dispatch(setIsPlayerTurn(true));
    }
  };

  // 处理弃牌
  const handleFold = async () => {
    try {
      setLocalError(null);
      dispatch(clearError());
      
      dispatch(updatePlayerActions({
        canCheck: false,
        canCall: false,
        canRaise: false,
        canFold: false,
        canAllIn: false
      }));
      dispatch(setIsPlayerTurn(false));
      
      await gameService.makeGameAction(gameId, { 
        type: 'fold',
        playerId: currentPlayerId
      });
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '弃牌失败';
      console.error('Fold failed:', error);
      setLocalError(errorMessage);
      
      // 恢复按钮状态
      dispatch(updatePlayerActions({
        canCheck,
        canCall,
        canRaise,
        canFold,
        canAllIn
      }));
      dispatch(setIsPlayerTurn(true));
    }
  };

  // 处理全押
  const handleAllIn = async () => {
    try {
      setLocalError(null);
      dispatch(clearError());
      
      setAllInDialogOpen(false);
      
      dispatch(updatePlayerActions({
        canCheck: false,
        canCall: false,
        canRaise: false,
        canFold: false,
        canAllIn: false
      }));
      dispatch(setIsPlayerTurn(false));
      
      await gameService.makeGameAction(gameId, { 
        type: 'all-in',
        playerId: currentPlayerId
      });
      
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '全押失败';
      console.error('All-in failed:', error);
      setLocalError(errorMessage);
      
      // 恢复按钮状态
      dispatch(updatePlayerActions({
        canCheck,
        canCall,
        canRaise,
        canFold,
        canAllIn
      }));
      dispatch(setIsPlayerTurn(true));
    }
  };

  // 计算最小和最大加注金额
  const minRaise = Math.max(currentBet * 2, bigBlind * 2); // 使用大盲注的2倍作为最小加注
  const maxRaise = playerChips;

  return (
    <Paper elevation={3} sx={{ p: 2 }}>
      <Typography variant="h6" gutterBottom>
        游戏操作
      </Typography>
      
      {/* 错误提示 */}
      {(localError || error) && (
        <Alert 
          severity="error" 
          sx={{ mb: 2 }}
          onClose={() => {
            setLocalError(null);
            dispatch(clearError());
          }}
        >
          {localError || error}
        </Alert>
      )}
      
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
        {/* 过牌按钮 */}
        <Button
          variant="contained"
          color="primary"
          onClick={handleCheck}
          disabled={!canCheck || isLoading}
          fullWidth
        >
          过牌
        </Button>

        {/* 跟注按钮 */}
        <Button
          variant="contained"
          color="success"
          onClick={handleCall}
          disabled={!canCall || isLoading}
          fullWidth
        >
          跟注 (${currentBet})
        </Button>

        {/* 加注按钮 */}
        <Button
          variant="contained"
          color="warning"
          onClick={() => setRaiseDialogOpen(true)}
          disabled={!canRaise || isLoading}
          fullWidth
        >
          加注
        </Button>

        {/* All In 按钮 */}
        <Button
          variant="contained"
          color="secondary"
          onClick={() => setAllInDialogOpen(true)}
          disabled={!canAllIn || isLoading}
          fullWidth
        >
          All In
        </Button>

        {/* 弃牌按钮 */}
        <Button
          variant="contained"
          color="error"
          onClick={handleFold}
          disabled={!canFold || isLoading}
          fullWidth
        >
          弃牌
        </Button>
      </Box>

      {/* 加注对话框 */}
      <Dialog open={raiseDialogOpen} onClose={() => setRaiseDialogOpen(false)}>
        <DialogTitle>加注金额</DialogTitle>
        <DialogContent>
          <Typography gutterBottom>
            选择加注金额: ${raiseAmount}
          </Typography>
          <Slider
            value={raiseAmount}
            onChange={(_, value) => setRaiseAmount(value as number)}
            min={minRaise}
            max={maxRaise}
            step={bigBlind} // 使用大盲注作为步长
            valueLabelDisplay="auto"
            valueLabelFormat={(value) => `$${value}`}
          />
          <TextField
            type="number"
            label="自定义金额"
            value={raiseAmount}
            onChange={(e) => setRaiseAmount(Number(e.target.value))}
            inputProps={{ min: minRaise, max: maxRaise }}
            fullWidth
            margin="normal"
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setRaiseDialogOpen(false)}>取消</Button>
          <Button onClick={handleRaise} variant="contained" color="primary">
            确认加注
          </Button>
        </DialogActions>
      </Dialog>

      {/* All In 确认对话框 */}
      <Dialog open={allInDialogOpen} onClose={() => setAllInDialogOpen(false)}>
        <DialogTitle>确认 All In</DialogTitle>
        <DialogContent>
          <Typography>
            您确定要 All In 吗？这将下注您所有的 ${playerChips} 筹码。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setAllInDialogOpen(false)}>取消</Button>
          <Button onClick={handleAllIn} variant="contained" color="secondary">
            确认 All In
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* 错误提示 Snackbar */}
      <Snackbar
        open={!!(localError || error)}
        autoHideDuration={6000}
        onClose={() => {
          setLocalError(null);
          dispatch(clearError());
        }}
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          severity="error" 
          onClose={() => {
            setLocalError(null);
            dispatch(clearError());
          }}
        >
          {localError || error}
        </Alert>
      </Snackbar>
    </Paper>
  );
};

export default GameControls;